import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from '@/components/ui/accordion';
import { Checkbox } from '@/components/ui/checkbox';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { cn } from '@/lib/utils';
import type { ProductInfo } from '@/lib/dianxiaomi';
import { OperationMessage, OperationMessageData, OperationMessageType } from '@/store/message';
import { CircleCheck, CircleX, BookText, Info } from 'lucide-react';
import { GigaProductDetialInfo } from '@/lib/giga';

export const doneMessage = 'done';

export type OperationMessagesCategoredItem =
  | {
      category: string;
      children: OperationMessage[];
    }
  | OperationMessage;

type OperationMessagesCategored = OperationMessagesCategoredItem[];

export function MessageIcon({
  type,
  className,
}: {
  type: OperationMessageType;
  className?: string;
}) {
  if (type === OperationMessageType.info) {
    return <Info className={cn(className)} size="16"></Info>;
  }
  if (type === OperationMessageType.success) {
    return <CircleCheck className={cn(className)} size="16"></CircleCheck>;
  }
  if (type === OperationMessageType.error) {
    return <CircleX className={cn(className)} size="16"></CircleX>;
  }
  if (type === OperationMessageType.verbose) {
    return <BookText className={cn(className)} size="16"></BookText>;
  }
}

export function RenderProductInfo({ productInfo }: { productInfo: ProductInfo }) {
  return <div className="whitespace-pre">{JSON.stringify(productInfo, null, 4)}</div>;
}

export function GigaProductInfo({ gigaProductInfo }: { gigaProductInfo: GigaProductDetialInfo }) {
  return <div className="whitespace-pre">{JSON.stringify(gigaProductInfo, null, 4)}</div>;
}

export function MessageData({ data }: { data: OperationMessageData }) {
  // console.log(data);
  if (data.kind === '产品信息') {
    return <RenderProductInfo productInfo={data.data}></RenderProductInfo>;
  }
  if (data.kind === 'GIGA 产品信息') {
    return <GigaProductInfo gigaProductInfo={data.data}></GigaProductInfo>;
  }
}

function getColor(type: OperationMessageType) {
  if (type === OperationMessageType.info) {
    return '';
  }
  if (type === OperationMessageType.success) {
    return 'hsl(142.1 76.2% 36.3%)';
  }
  if (type === OperationMessageType.error) {
    return 'red';
  }
  if (type === OperationMessageType.verbose) {
    return '';
  }
}

export default function BaseOperationMessages({
  className,
  categoryItemActionRenderer,
  operationMessages,
  ...props
}: {
  className: string;
  categoryItemActionRenderer: (message: OperationMessagesCategoredItem) => React.ReactNode;
  operationMessages: OperationMessage[];
} & React.HTMLAttributes<HTMLDivElement>) {
  const [fileterType, setFilterType] = useState<OperationMessageType[]>([
    OperationMessageType.info,
    OperationMessageType.success,
    OperationMessageType.error,
  ]);
  const appConfig = useAppConfig();

  // 过滤需要的类型信息
  // const operationFilterMessages = operationMessages.filter((message) => {
  //   return fileterType.includes(message.type);
  // });

  // 对分类相同的信息进行分类
  const operationMessagesCategored = operationMessages.reduce((acc, message) => {
    const category = message.category;
    if (category === appConfig.topMessageCategoryName) {
      acc.push(message);
    } else {
      const catetroyItem = acc.find((item) => item.category === category);
      if (catetroyItem) {
        (
          catetroyItem as {
            category: string;
            children: OperationMessage[];
          }
        ).children.push(message);
      } else {
        acc.push({
          category: message.category,
          children: [message],
        });
      }
    }
    return acc;
  }, [] as OperationMessagesCategored);

  // console.log(operationMessagesCategored);

  // 获取目录成员类型,取最后一个信息的类型。
  const getCatetoryItemType = (category: string) => {
    const lastMessage = operationMessages.findLast((message) => {
      return message.category === category;
    });
    if (lastMessage) {
      const message = lastMessage.message;
      if (message.includes(doneMessage)) {
        return OperationMessageType.success;
      }
      if (lastMessage.type !== OperationMessageType.success) {
        return lastMessage.type;
      }
    }
    return OperationMessageType.info;
  };

  return (
    <div {...props} className={cn(className, 'flex flex-col')}>
      <div className="flex mb-2 justify-end">
        {Object.keys(OperationMessageType).map((key) => {
          if (!Number.isNaN(parseInt(key))) {
            return null;
          }
          return (
            <div className="flex items-center ml-2 mr-2 gap-2" key={key}>
              <Checkbox
                checked={fileterType.includes(
                  OperationMessageType[key as keyof typeof OperationMessageType],
                )}
                onCheckedChange={(state) => {
                  if (state) {
                    // fileterType 增加对应的成员
                    setFilterType([
                      ...fileterType,
                      OperationMessageType[key as keyof typeof OperationMessageType],
                    ]);
                  } else {
                    setFilterType(
                      fileterType.filter(
                        (item) =>
                          item !== OperationMessageType[key as keyof typeof OperationMessageType],
                      ),
                    );
                  }
                }}
                id={`${key}-messege-type`}
                className="rounded-[2px]"
              />
              <label
                htmlFor={`${key}-messege-type`}
                className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 mb-0"
              >
                {key}
              </label>
            </div>
          );
        })}
      </div>
      <div className="grow relative group">
        <ScrollArea className="border rounded-sm h-full w-full p-2 [.group_&]:!absolute [.group_&]:!h-full [&_[data-radix-scroll-area-viewport]]:!h-full [&_[data-radix-scroll-area-viewport]]:!overflow-auto">
          <Accordion type="multiple" className="w-full">
            {operationMessagesCategored
              .filter((categoryItem) => {
                if ('children' in categoryItem) {
                  return true;
                }
                return fileterType.includes(categoryItem.type);
              })
              .map((categoryItem, index) => {
                return (
                  <div key={`${categoryItem.category}-${index}`} className="leading-loose py-1">
                    {'children' in categoryItem && categoryItem.children.length > 0 ? (
                      <AccordionItem value={`${categoryItem.category}`}>
                        <AccordionTrigger
                          style={{ color: getColor(getCatetoryItemType(categoryItem.category)) }}
                          className="flex items-center gap-2 justify-start py-0 !flex-nowrap"
                        >
                          <MessageIcon
                            type={getCatetoryItemType(categoryItem.category)}
                            className="!rotate-0"
                          ></MessageIcon>
                          <div className="whitespace-nowrap">
                            {categoryItemActionRenderer(categoryItem)}
                          </div>
                        </AccordionTrigger>
                        <AccordionContent className="pl-4">
                          <Accordion type="multiple" className="w-full">
                            {categoryItem.children
                              .filter((message) => fileterType.includes(message.type))
                              .map((message, index) => {
                                return (
                                  <div key={message.id} className="leading-loose">
                                    {message.data ? (
                                      <AccordionItem value={`item-${index}`}>
                                        <AccordionTrigger
                                          className="flex items-center gap-2 justify-start py-0 !flex-nowrap"
                                          style={{
                                            color: getColor(message.type),
                                          }}
                                        >
                                          <MessageIcon
                                            type={message.type}
                                            className="!rotate-0"
                                          ></MessageIcon>
                                          <span className="whitespace-nowrap">
                                            {message.message}
                                          </span>
                                        </AccordionTrigger>
                                        <AccordionContent>
                                          <MessageData data={message.data}></MessageData>
                                        </AccordionContent>
                                      </AccordionItem>
                                    ) : (
                                      <div
                                        className="flex items-center gap-2 !flex-nowrap"
                                        style={{
                                          color: getColor(message.type),
                                        }}
                                      >
                                        <MessageIcon type={message.type}></MessageIcon>
                                        <span className="whitespace-nowrap">{message.message}</span>
                                      </div>
                                    )}
                                  </div>
                                );
                              })}
                          </Accordion>
                        </AccordionContent>
                      </AccordionItem>
                    ) : (
                      <div
                        className="flex items-center gap-2 !flex-nowrap leading-none"
                        style={{
                          color: getColor((categoryItem as OperationMessage).type),
                        }}
                      >
                        <MessageIcon type={(categoryItem as OperationMessage).type}></MessageIcon>
                        <span className="whitespace-nowrap">
                          {(categoryItem as OperationMessage).message}
                        </span>
                      </div>
                    )}
                  </div>
                );
              })}
          </Accordion>
          <ScrollBar orientation="horizontal"></ScrollBar>
        </ScrollArea>
      </div>
    </div>
  );
}
